package cn.suimg.wechat.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;


/**
 * Spring Security 配置
 * @author Suimg
 */
@EnableWebSecurity
@EnableOAuth2Sso
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {


    @Value("${cn.suimg.sso.access-denied.anonymous}")
    private String anonymousUrl;

    @Value("${cn.suimg.sso.access-denied.permission-denied}")
    private String permissionDeniedUrl;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/user/**").authenticated()
                .and()

                //.and()
                //.formLogin().loginPage("/login/index.do")

                .logout()
                .logoutUrl("/login/logout.do")
                .logoutSuccessUrl("https://sso.suimg.cn/logout/index.do")
                .deleteCookies("JSESSIONID")
                .and()

                .csrf().disable()

                .exceptionHandling()
                //转发到提示需要认证的页面
                .authenticationEntryPoint((request, response, authException) -> request.getRequestDispatcher(anonymousUrl).forward(request,response))
                //拒绝访问。
                .accessDeniedHandler((request, response, authException) -> response.sendRedirect(permissionDeniedUrl))
        ;
    }

    @Bean
    public OAuth2RestTemplate oAuth2RestTemplate(OAuth2ClientContext oAuth2ClientContext, OAuth2ProtectedResourceDetails details){
        return new OAuth2RestTemplate(details,oAuth2ClientContext);
    }

}
